/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.service;

import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.fee.entity.Consignor;
import com.jeeplus.modules.fee.entity.ShippingAddress;
import com.jeeplus.modules.fee.mapper.ConsignorMapper;
import com.jeeplus.modules.fee.mapper.ShippingAddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 下游客户Service
 * @author weisong
 * @version 2017-10-10
 */
@Service
@Transactional(readOnly = true)
public class ConsignorService extends CrudService<ConsignorMapper, Consignor> {

	@Autowired
	private ShippingAddressMapper shippingAddressMapper;
	
	public Consignor get(String id) {
		Consignor consignor = super.get(id);
		consignor.setShippingAddressList(shippingAddressMapper.findList(new ShippingAddress(consignor)));
		return consignor;
	}
	
	public List<Consignor> findList(Consignor consignor) {
		return super.findList(consignor);
	}
	
	public Page<Consignor> findPage(Page<Consignor> page, Consignor consignor) {
		return super.findPage(page, consignor);
	}
	
	@Transactional(readOnly = false)
	public void save(Consignor consignor) {
		super.save(consignor);
		for (ShippingAddress shippingAddress : consignor.getShippingAddressList()){
			if (shippingAddress.getId() == null){
				continue;
			}
			if (ShippingAddress.DEL_FLAG_NORMAL.equals(shippingAddress.getDelFlag())){
				if (StringUtils.isBlank(shippingAddress.getId())){
					shippingAddress.setFeeConsignor(consignor);
					shippingAddress.preInsert();
					shippingAddressMapper.insert(shippingAddress);
				}else{
					shippingAddress.preUpdate();
					shippingAddressMapper.update(shippingAddress);
				}
			}else{
				shippingAddressMapper.delete(shippingAddress);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Consignor consignor) {
		super.delete(consignor);
		shippingAddressMapper.delete(new ShippingAddress(consignor));
	}

	//根据名称查询
	public Consignor findByName(String name){
		List<Consignor> list = mapper.findByName(name);
		return null!=list&&list.size()>0 ? list.get(0) : null;
	}
	//查询所有的id和name （下拉框用）
	public List<Consignor> findIdAndName(){
		return mapper.findIdAndName();
	}
}